<?php
namespace app\controller;

use app\controller\Base;
use app\model\ArticleModel;
use app\model\MessageModel;
use app\model\QueryModel;
use app\model\WanjiaArticleModel;
use app\model\WanjiaSpecialArticleModel;
use app\model\WanjiaVideoModel;
use app\service\AiService;
use app\service\UpdateFileService;
use think\facade\Db;
use support\Request;
use support\View;
use tool\Wxin;
use Workerman\Protocols\Http\Chunk;
use Workerman\Connection\TcpConnection;
use Workerman\Protocols\Http\ServerSentEvents;
use Workerman\Timer;

class IndexController extends Base
{
    protected function generateUniqueRandomStrings(int $count = 1500): array {
        $chars = 'abcdefghijklmnopqrstuvwxyz0123456789'; // 字符集（小写字母+数字）
        $charLength = strlen($chars); // 字符集长度（36）
        $result = [];       // 存储最终结果
        $exists = [];       // 哈希表用于快速校验重复（键为生成的字符串）

        while (count($result) < $count) {
            $randomStr = '';
            // 生成 6 位随机字符
            for ($i = 0; $i < 6; $i++) {
                // 随机选取字符集中的字符（mt_rand 比 rand 更随机）
                $randomIndex = mt_rand(0, $charLength - 1);
                $randomStr .= $chars[$randomIndex];
            }

            // 校验是否已存在，不存在则加入结果
            if (!isset($exists[$randomStr])) {
                $exists[$randomStr] = true;  // 标记为已存在
                $result[] = $randomStr;      // 加入结果数组
            }
        }

        return $result;
    }
    public function index(Request $request)
    {
        $wechat = new Wxin();
        // if ($wechat->verifyToken($request->all())) {
        //     return response($request->input('echostr', ''));
        // }
        // return response('验证失败', 403);

        $url = $request->header('x-forwarded-proto').':'.$request->fullUrl();
        $signPackage = $wechat->getSignPackage($url);
        View::assign('sign',$signPackage);


        //这里请使用缓存
        if(isMobile() and $this->system['is_mob']=='启用'){
            return view('index/m_index');
        }else{
            return view('index/index');
        }
    }
    public function cate(Request $request,$id)
    {
        $wechat = new Wxin();
        $url = $request->header('x-forwarded-proto').':'.$request->fullUrl();
        $signPackage = $wechat->getSignPackage($url);
        View::assign('sign',$signPackage);


        $id=intval($id);
        //拦截远程跳转
        $cate=Db::name('cate')->where('id',$id)->find();
        if($cate['type']==4 and isset($cate['url'])){
            return redirect($cate['url']);
        }
        $html=$cate['catehtml'];
        View::assign('id', input('id'));
        if(substr($html,-5,5)=='.html'){
            $html=substr($html,0,strlen($html)-5);
        }
        if($html){
            if(isMobile() and $this->system['is_mob']=='启用'){
                return view('index/m_'.$html);
            }else{
                return view('index/'.$html);
            }
        }else{
            if(isMobile() and $this->system['is_mob']=='启用'){
                return view('index/m_cate');
            }else{
                return view('index/cate');
            }
        }
    }
    public function search(Request $request)
    {
        $keyword=$request->input('key','');
        $cateid=$request->input('cateid',0);
        $num=$request->input('num',10);
        $catename='全部';
        $where=true;
        if($cateid){
            $catename=Db::name('cate')->where('id',$cateid)->value('catename');
            $where=[
                'cateid'=>$cateid
            ];
        }
        $list=ArticleModel::where('isopen',1)->where($where)->where('title','like','%'.$keyword.'%')->paginate(['list_rows'=>$num,'query'=>request()->all()]);
        $page = $list->render();
        // 模板变量赋值
        View::assign('list', $list);
        View::assign('page', $page);

        $dataindex=[
            'catename'=>'搜索',
            'en_name'=>'search',
            'fid'=>0,
            'cateid'=>0
        ];
        View::assign('data', $dataindex);

        if(isMobile() and $this->system['is_mob']=='启用'){
            return view('index/m_search',[
                'key'=>$keyword,
                'catename'=>$catename,
            ]);
        }else{
            return view('index/search',[
                'key'=>$keyword,
                'catename'=>$catename,
            ]);
        }
    }
    public function shuoming(Request $request,$id)
    {
        $id=intval($id);
        $article=Db::name('shuoming')->where('id',$id)->find();
        if(!$article){
            return redirect('/404.html');
        }
        if(isset($article['url']) and $article['url']){
            return redirect($article['url']);
        }
        Db::name('shuoming')->where('id',$article['id'])->update([
            'click_wai'=>$article['click_wai']+1,
            'click'=>$article['click']+1,
        ]);
        if(isMobile() and $this->system['is_mob']=='启用'){
            return view('index/m_shuoming',[
                'data'=>$article
            ]);
        }else{
            return view('index/shuoming',[
                'data'=>$article
            ]);
        }
    }
    public function show(Request $request,$id)
    {

        $wechat = new Wxin();
        $url = $request->header('x-forwarded-proto').':'.$request->fullUrl();
        $signPackage = $wechat->getSignPackage($url);
        View::assign('sign',$signPackage);


        $article = new ArticleModel();
        $id=intval($id);
        $article=$article->where('id',$id)->find();
        if(!$article){
            return redirect('/404.html');
        }
        if(isset($article['url']) and $article['url']){
            return redirect($article['url'],302);
        }
        $article->where('id',$article['id'])->update([
            'click_wai'=>$article['click_wai']+1,
            'click'=>$article['click']+1,
        ]);

        $shang1=$article->where('id','<',$id)->where('cateid',$article['cateid'])->order('id desc')->find();
        if($shang1){
            $shang="<a href='".route('index.show',['id'=>$shang1['id']])."'>".$shang1['title']."</a>";
            $shangurl=route('index.show',['id'=>$shang1['id']]);
        }else{
            $shang="<a href='".route('index.cate',['id'=>$article['cateid']])."'>返回列表</a>";
            $shangurl=route('index.cate',['id'=>$article['cateid']]);
        }
        $xia1=$article->where('id','>',$id)->where('cateid',$article['cateid'])->order('id asc')->find();
        if($xia1){
            $xia="<a href='".route('index.show',['id'=>$xia1['id']])."'>".$xia1['title']."</a>";
            $xiaurl=route('index.show',['id'=>$xia1['id']]);
        }else{
            $xia="<a href='".route('index/cate',['id'=>$article['cateid']])."'>返回列表</a>";
            $xiaurl=route('index.cate',['id'=>$article['cateid']]);
        }
        View::assign([
            'shang'=>$shang,
            'xia'=>$xia,
            'shangurl'=>$shangurl,
            'xiaurl'=>$xiaurl,
            'data'=>$article,
        ]);
        $html=Db::name('cate')->where('id',$article['cateid'])->value('showhtml');
        if(substr($html,-5,5)=='.html'){
            $html=substr($html,0,strlen($html)-5);
        }
        if($html){
            if(isMobile() and $this->system['is_mob']=='启用'){
                return view('index/m_'.$html);
            }else{
                return view('index/'.$html);
            }
        }else{
            if(isMobile() and $this->system['is_mob']=='启用'){
                return view('index/m_show');
            }else{
                return view('index/show');
            }
        }
    }

    public function share(Request $request,$id,$type)
    {
        $wechat = new Wxin();
        $url = $request->header('x-forwarded-proto').':'.$request->fullUrl();
        $signPackage = $wechat->getSignPackage($url);
        View::assign('sign',$signPackage);
        if($type==1){
            $one=WanjiaArticleModel::where('id',$id)->find();
        }
        if($type==2){
            $one=WanjiaVideoModel::where('id',$id)->find();
        }
        if($type==3){
            $one=WanjiaSpecialArticleModel::where('id',$id)->find();
        }
        View::assign([
            'data'=>$one,
        ]);
        return view('index/share');
    }

    public function update(Request $request)
    {
        if($request->method()=='POST'){
            $data=$request->post();
            $validate = new \app\validate\UpdateValidate;
            if (!$validate->check($data)) {
                return view_e($validate->getError());
            }
            if($data['type']=='message'){
                $message=new MessageModel();
                $res=$message->save([
                    'title'=>$data['title'],
                    'name'=>$data['loginname'],
                    'phone'=>$data['phone'],
                    'neirong'=>$data['need']
                ]);
                if($res){
                    return view_s('留言成功');
                }else{
                    return view_e('留言失败');
                }
            }
        }
        return redirect('/');
    }
    //富文本上传
    public function richTextUpload(Request $request)
    {
        $all=$request->all();
        if($all['action']=='config'){
            $config = [
                "imageActionName"=> "uploadimage",
                "imageFieldName"=>  "file",
                "imageMaxSize"=>  2048000, // 文件大小限制
                "imageAllowFiles"=>  [".png", ".jpg", ".jpeg",'.gif','.webp'],
                "imageUrlPrefix"=>  "" // 返回URL不带前缀
            ];
            return json($config);
        }
        if($all['action']=='uploadimage'){
            $file = $request->file('file');
            if ($file && $file->isValid()  && $getSize=$file->getSize() >0) {
                if(!in_array($file->getUploadExtension(), ['jpg','png','gif','webp','jpeg'])){
                    return json(['state'=>'图片格式不正确']);
                }
                if($getSize > 5*1024*1024){
                    return json(['state'=>'图片大小不能超过5M']);
                }
                $path = '/richText/'.date("YmdHis").rand(10000,99999).session('uid', '0').'.'.$file->getUploadExtension();
                $file->move(public_path().$path);
                return json([
                    "state"=> "SUCCESS",
                    "url"=> $path,
                    "title"=> $file->getUploadName(),
                    "original"=> $file->getUploadName(),
                    "type"=> $file->getUploadExtension(),
                    "size"=> $getSize
                ]);
            }
        }
        s();
    }
    public function query(Request $request)
    {
        $username=$request->get('username','');
        $no=$request->get('no','');
        if(!$no or !$username){
            return view_e('查询失败');
        }
        $wo= QueryModel::where('name',$username)->where('no',$no)->where('isopen',1)->find();
        if(!$wo){
            return view_e('查询失败');
        }
        return view('index/ql',[
            'data'=>$wo
        ]);


    }
}
